import React, { useEffect, useState, useMemo } from "react";
import request from "../../api/request";
import style from "./index.module.css";
import { Card } from "antd-mobile";
type ZongheProps = {
  keyword?: string;
  onResult?: (hasAnyResult: boolean) => void;
  onTabChange?: (tabKey: string) => void;
};

function Index({ keyword = "", onResult, onTabChange }: ZongheProps) {
  const [books, setBooks] = useState<any[]>([]);
  const [doctors, setDoctors] = useState<any[]>([]);
  const [hospitals, setHospitals] = useState<any[]>([]);
  const [socal, setSocal] = useState<any[]>([]);

  const [pageCode] = useState(1);
  const [pageSize] = useState(10);
  const [searchValue, setSearchValue] = useState("");

  const getSearch = async () => {
    const res: any = await request.get("/api/search", {
      params: {
        pageCode,
        pageSize: 2,
        searchValue,
      },
    });
    console.log("搜索内容", res);
    if (res.code === 20000) {
      setBooks(res.data.book);
      setDoctors(res.data.doctor);
      setSocal(res.data.soco);
    }
    console.log("book", res.data.book);
    console.log("doctor", res.data.doctor);
    console.log("soco", res.data.soco);
  };

  const getHospitals = async () => {
    const res: any = await request.get("/api/restorative/list", {
      params: {
        pageCode,
        pageSize: 2,
      },
    });
    console.log("医院", res);
    if (res.code === 200) {
      setHospitals(res.data);
    }
  };

  useEffect(() => {
    getHospitals();
  }, []);

  // 关键字变化时更新并触发搜索
  useEffect(() => {
    setSearchValue(keyword);
  }, [keyword]);

  useEffect(() => {
    getSearch();
  }, [searchValue, pageCode]);

  // 统一的小写包含判断
  const normalize = (val: any) => (val == null ? "" : String(val)).toLowerCase();
  const kw = normalize(keyword).trim();

  const filteredBooks = useMemo(() => {
    if (!kw) return books;
    return books.filter((item) => {
      return (
        normalize(item.texttitle).includes(kw) ||
        normalize(item.textdescword).includes(kw) ||
        normalize(item.texttype).includes(kw)
      );
    });
  }, [books, kw]);

  const filteredDoctors = useMemo(() => {
    if (!kw) return doctors;
    return doctors.filter((item) => {
      return (
        normalize(item.doctorname).includes(kw) ||
        normalize(item.doctorstate).includes(kw) ||
        normalize(item.doctorcity).includes(kw) ||
        normalize(item.doctoradministre).includes(kw) ||
        normalize(item.doctordescword).includes(kw)
      );
    });
  }, [doctors, kw]);

  const filteredHospitalsSection = useMemo(() => {
    // "相关医院" 实际来自 socal
    if (!kw) return socal;
    return socal.filter((item) => {
      return (
        normalize(item.sococity).includes(kw) ||
        normalize(item.socolv).includes(kw) ||
        normalize(item.nosocomium).includes(kw)
      );
    });
  }, [socal, kw]);

  const filteredDrugs = useMemo(() => {
    // "相关药品" 实际来自 hospitals（restoratives）
    if (!kw) return hospitals;
    return hospitals.filter((item) => {
      return (
        normalize(item.restorativesname).includes(kw) ||
        normalize(item.restorativesdesc).includes(kw)
      );
    });
  }, [hospitals, kw]);

  const allEmpty =
    filteredBooks.length === 0 &&
    filteredDoctors.length === 0 &&
    filteredHospitalsSection.length === 0 &&
    filteredDrugs.length === 0;

  // 将是否有结果上报给父组件
  useEffect(() => {
    if (onResult) {
      onResult(!allEmpty);
    }
  }, [allEmpty, onResult]);

  return (
    <div>
      {filteredBooks.length > 0 && (
        <Card className={style.card1}>
          <div className={style.h3}>
            <h3 onClick={() => onTabChange?.("2")}>相关科普</h3> <span onClick={() => onTabChange?.("2")}>查看更多＞</span>
          </div>

          {filteredBooks.map((item, index) => (
            <div key={index} className={style.cardBox1}>
              <p className={style.textmsg1}>
                {item.texttitle?.substring(0, 15)}
              </p>
              <p className={style.textdescword}>{item.textdescword}</p>

              <div className={style.textdess}>
                <div className={style.textdess1}>
                  <span>聂里红</span>|<span>北京中医药大学东直门医院</span>
                  <span>消化科</span>
                </div>

                <span className={style.textArt}>{item.texttype}</span>
              </div>
            </div>
          ))}

          <div></div>
        </Card>
      )}

      {filteredDoctors.length > 0 && (
        <Card className={style.card2}>
          <div className={style.h3}>
            <h3 onClick={() => onTabChange?.("3")}>相关医生</h3> <span onClick={() => onTabChange?.("3")}>查看更多＞</span>
          </div>

          {filteredDoctors.map((item, index) => (
            <div key={index} className={style.carddoct}>
              <div className={style.doctorBox1}>
                <img src={item.doctorimage} alt="" />

                <div>
                  <div className={style.diplay5}>
                    <h4>{item.doctorname}</h4>
                    <span>{item.doctorstate}</span>
                  </div>

                  <div className={style.diplay1}>
                    <span>{item.doctorcity}</span>
                    <span>{item.doctoradministre}</span>
                  </div>

                  <span className={style.tuwen}>图文咨询</span>

                  <p className={style.textShan}>擅长:{item.doctordescword}</p>

                  <div className={style.diplay4}>
                    <span className={style.diplay2}>
                      好评率:<p>{item.doctorgood}%</p>
                    </span>
                    |<span>锦旗{2}</span>|<span>浏览人次{item.doctoradmin}</span>
                  </div>

                  <div className={style.diplay3}>
                    <span>{<b>￥{item.doctorprice}</b>}起</span>
                    <span className={style.ansower}>问医生</span>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </Card>
      )}

      {filteredHospitalsSection.length > 0 && (
        <Card className={style.card2}>
          <div className={style.h3}>
            <h3 onClick={() => onTabChange?.("4")}>相关医院</h3> <span onClick={() => onTabChange?.("4")}>查看更多＞</span>
          </div>

          {filteredHospitalsSection.map((item, index) => (
            <div key={index} className={style.socoBox}>
              <img src={item.socoimage} alt="" />

              <div>
                <p className={style.hosp}>{item.sococity}</p>
                <p className={style.hosps}>
                  <span>{item.socolv}</span>
                  <span>{item.nosocomium}</span>
                </p>
              </div>
            </div>
          ))}
        </Card>
      )}

      {filteredDrugs.length > 0 && (
        <Card className={style.card2}>
          <div className={style.h3}>
            <h3 onClick={() => onTabChange?.("5")}>相关药品</h3> <span onClick={() => onTabChange?.("5")}>查看更多＞</span>
          </div>

          {filteredDrugs.map((item, index) => (
            <div key={index} className={style.socoBox1}>
              <img src={item.restorativesimage} alt="" />

              <div className={style.right}>
                <div className={style.titleRow}>
                  <span className={style.otc}>OTC</span>
                  <span className={style.otcright}>{item.restorativesname}</span>
                </div>

                <p className={style.yinc}>{item.restorativesdesc}</p>

                <span className={style.prices}>￥{item.restorativesprice}</span>
              </div>
            </div>
          ))}
        </Card>
      )}

      {/* 注意：根据最新需求，父级会在无结果时隐藏整个内容，因此此处空态不再显示 */}
    </div>
  );
}

export default Index;
